package com.lysj.bhp.api.controller;

import com.lysj.bhp.api.base.ApiContent;
import com.lysj.bhp.coinexchange.domain.BhpcRecord;
import com.lysj.bhp.coinexchange.dto.BhpcRecordDto;
import com.lysj.bhp.coinexchange.vo.BhpcRecordVo;
import com.lysj.bhp.financial.domain.Financial;
import com.lysj.bhp.financial.domain.UserEarnings;
import com.lysj.bhp.financial.dto.UserFinancialRecordDto;
import com.lysj.bhp.financial.vo.UserFinancialRecordVo;
import com.lysj.bhp.recharge.domain.RechargeRecord;
import com.lysj.bhp.util.random.FormatUtil;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import com.lysj.bhp.wallet.domain.BhpcWallet;
import com.lysj.bhp.wallet.domain.BitCoinWallet;
import com.lysj.bhp.wallet.domain.EthereumWallet;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/v2/user")
@Api(value = "ApiPackageFinancialController", tags = "理财包模块")
public class ApiPackageFinancialController extends ApiContent {


    @InitBinder
    public void InitBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }

    //查询理财记录
    @ApiOperation(value = "收益记录", notes = "查询条件理财起始时间,收益返还方式,参数:begin_interestDate,end_interestDate,purchasedCurrency:10:比特币;20:以太坊;100:BHPC;")
    @PostMapping("/earnings_record")
    public Resp earningsRecord(UserFinancialRecordDto model) {
        //查询条件数据为空,进行初始化操作
        if (ParamUtil.isBlack(model.getLimit())) {
            model.setLimit(10);
        }
        if (ParamUtil.isBlack(model.getPage())) {
            model.setPage(0);
        }
        if (ParamUtil.isBlack(model.getEarningsType())) {
            model.setEarningsType(10);
        }
        if (model.getBegin_interestDate() == null) {
            model.setBegin_interestDate(FormatUtil.addDay(new Date(), -30));
        } else {
            model.setBegin_interestDate(FormatUtil.getDayStartDay(model.getBegin_interestDate()));
        }
        if (model.getEnd_interestDate() == null) {
            model.setEnd_interestDate(FormatUtil.getDayEndDay(new Date())); //  获取到今天的结束
        } else {
            model.setEnd_interestDate(FormatUtil.getDayEndDay(model.getEnd_interestDate()));
        }

        //获取根据时间以及币种查询出的充值记录
        Pageable pageable = new PageRequest(model.getPage(), model.getLimit());
        Page<UserFinancialRecordVo> userFinancialRecordVoPage = userFinancialRecordRepository.findUserFinancialRecord(pageable, model.getEarningsType(), model.getBegin_interestDate(), model.getEnd_interestDate(), currentUser().getUserId());
        for (UserFinancialRecordVo userFinancialRecordVo : userFinancialRecordVoPage) {
            if (10 == userFinancialRecordVo.getEarningsType()) {
                userFinancialRecordVo.setEarningsDivide(userFinancialRecordVo.getDivide() + "BTC");
            } else if (20 == userFinancialRecordVo.getEarningsType()) {
                userFinancialRecordVo.setEarningsDivide(userFinancialRecordVo.getDivide() + "ETH");
            } else if (100 == userFinancialRecordVo.getEarningsType()) {
                userFinancialRecordVo.setEarningsDivide(userFinancialRecordVo.getDivide() + "BHPC");
            }
            userFinancialRecordVo.setEndIntersetDate(FormatUtil.addDay(userFinancialRecordVo.getEndIntersetDate(),-1));
        }
        Map<String, Object> respMap = new HashMap();
        respMap.put("totalpage", userFinancialRecordVoPage.getTotalPages());
        respMap.put("rows", userFinancialRecordVoPage.getContent());
        return new Resp(respMap);
    }


    //查询理财记录
    @ApiOperation(value = "进入理财界面", notes = "参数token,limit,page")
    @GetMapping("/financial_manage")
    public Resp financialManage(Integer limit, Integer page) {

        BigDecimal btcEarnings = new BigDecimal(BigInteger.ZERO); //BTC总收益
        BigDecimal ethEarnings = new BigDecimal(BigInteger.ZERO); //ETH总收益
        BigDecimal bhpcEarnings = new BigDecimal(BigInteger.ZERO); //BHPC总收益
        BigDecimal btcEarningsCny = new BigDecimal(BigInteger.ZERO); //BTC总收益(单位:CNY)
        BigDecimal ethEarningsCny = new BigDecimal(BigInteger.ZERO); //ETH总收益(单位:CNY)
        BigDecimal bhpcEarningsCny = new BigDecimal(BigInteger.ZERO); //BHPC总收益(单位:CNY)

        UserEarnings userEarnings = userEarningsRepository.findByUserId(currentUser().getUserId());
        if (null != userEarnings) {
            btcEarnings = userEarnings.getBtcEarnings();
            ethEarnings = userEarnings.getEthEarnings();
            bhpcEarnings = userEarnings.getBhpcEarnings();
            btcEarningsCny = btcEarnings.multiply(exchangeRate.getBITCOIN_TO_CNY()).setScale(6, BigDecimal.ROUND_DOWN);
            ethEarningsCny = ethEarnings.multiply(exchangeRate.getETH_TO_CNY()).setScale(6, BigDecimal.ROUND_DOWN);
            bhpcEarningsCny = bhpcEarnings.multiply(exchangeRate.getBHPC_TO_CNY()).setScale(6, BigDecimal.ROUND_DOWN);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("btcEarnings", btcEarnings);
        map.put("ethEarnings", ethEarnings);
        map.put("bhpcEarnings", bhpcEarnings);
        map.put("btcEarningsCny", btcEarningsCny);
        map.put("ethEarningsCny", ethEarningsCny);
        map.put("bhpcEarningsCny", bhpcEarningsCny);
        if (ParamUtil.isBlack(limit)) {
            limit = 6;
        }
        if (ParamUtil.isBlack(page)) {
            page = 0;
        }
        Pageable pageable = new PageRequest(page, limit);
        Page<Financial> financialPage = financialRepository.findByIsOnlineAndIsExist(1,1,pageable);
        map.put("totalpage", financialPage.getTotalPages());
        map.put("rows", financialPage.getContent());
        return new Resp(map);
    }

    //查询理财记录
    @ApiOperation(value = "购买理财", notes = "参数:理财包id,投资数量,financialId,investmentNum")
    @GetMapping("/financial_purchase")
    public Resp financialPurchase(Long financialId, BigDecimal investmentNum) {
        return financialPurchaseService.financialPurchase(financialId, investmentNum);
    }

    @ApiOperation(value = "显示理财详情", notes = "参数:理财包id,financialId")
    @GetMapping("/show_financial_detail")
    public Resp showFinancialDetail(Long financialId) {
        if (ParamUtil.isBlack(financialId)) {
            return new Resp(Resp.PARAM_ERROR, "请选择理财包");
        }
        Map<String, Object> map = new HashMap<>();
        Financial financial = financialRepository.findOne(financialId);
        if(null==financial){
            return new Resp(Resp.PARAM_ERROR, "理财包不存在");
        }
        map.put("financial", financial);
        map.put("availBalance", 0);
        if (10 == financial.getInvestmentType()) {
            BitCoinWallet bitCoinWallet = bitcoinWalletRepository.findByUserId(currentUser().getUserId());
            if (null != bitCoinWallet) {
                map.put("availBalance", bitCoinWallet.getAvailBalance());
            }
        }
        if (20 == financial.getInvestmentType()) {
            EthereumWallet ethereumWallet = ethereumWalletRepository.findByUserId(currentUser().getUserId());
            if (null != ethereumWallet) {
                map.put("availBalance", ethereumWallet.getAvailBalance());
            }
        }
        if (100 == financial.getInvestmentType()) {
            BhpcWallet bhpcWallet = bhpcWalletRepository.findByUserId(currentUser().getUserId());
            if (null != bhpcWallet) {
                map.put("availBalance", bhpcWallet.getAvailBalance());
            }
        }
        List<Financial> financialList = financialRepository.findByIsOnlineAndStatusAndLeftPortionGreaterThanAndIsExist(1,1,new BigDecimal(BigInteger.ZERO),1);
        //将所有理财产品打乱
        Collections.shuffle(financialList);
        //移除当前理财产品
        financialList.remove(financial);
        if(financialList.size()<3){
            financialList= financialList.subList(0, financialList.size());
        }else{
            financialList= financialList.subList(0, 3);
        }
        map.put("financialList", financialList);
        return new Resp(map);
    }


}
